package com.zzy.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {

    // 过滤器种类
    @Override
    public String filterType() {
        return "pre";
    }

    // 过滤器执行顺序,数字越小 执行时机越高
    @Override
    public int filterOrder() {
        return 0;
    }

    // 是否执行过滤器
    @Override
    public boolean shouldFilter() {
        // 获取上下文请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        // 判断是否以login/register结尾，包含就不执行登录业务校验，所以返回false
        if(uri.endsWith("login") || uri.endsWith("register")){
            return false;
        }
        return true;
    }


    @Override
    public Object run() throws ZuulException {
        // 1.获取请求的token
        RequestContext requestContext = RequestContext.getCurrentContext();
        String token = requestContext.getRequest().getHeader("token");

        HttpServletResponse response = requestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        // 2.判断有没有token
        if (!StringUtils.isEmpty(token)){
            try {
                // 如果没登陆 就响应
                PrintWriter writer = response.getWriter();
                HashMap<Object, Object> map = new HashMap<>();
                map.put("success",false);
                map.put("message","请你先登录");
                map.put("obj","noLogin");
                String string = JSONObject.toJSONString(map);
                writer.write(string);
                // 3. 阻止过滤器
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 返回什么都可以
        return null;
    }
}
